package com.hfjyz.tutor.tutor.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;

import com.hfjyz.base.action.GridBaseAction;
import com.hfjyz.base.exception.BaseException;
import com.hfjyz.base.util.BaseUtil;
import com.hfjyz.tutor.tutor.bean.TutorBean;
import com.hfjyz.tutor.tutor.bean.TutorExcelBean;
import com.hfjyz.tutor.tutor.bean.TutorSearchBean;
import com.hfjyz.tutor.tutor.service.TutorService;
import com.hfjyz.tutor.tutorcall.bean.TutorCallBean;
import com.hfjyz.tutor.tutorcall.service.TutorCallService;

public class TutorAutoSelectAction extends GridBaseAction {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 2363637918721745365L;

    private TutorSearchBean tutorSearch = null;
    private Integer autoSelectCount = null;
    private TutorCallBean tutorCall = null;
    private String tutorIds = null;

    private InputStream excelStream = null;
    private String downloadFileName = null;

    private TutorService service = null;

    private TutorCallService callService = null;

    public InputStream getExcelStream() {
        return excelStream;
    }

    public void setExcelStream(InputStream excelStream) {
        this.excelStream = excelStream;
    }

    public String getDownloadFileName() {
        return downloadFileName;
    }

    public void setDownloadFileName(String downloadFileName) {
        this.downloadFileName = downloadFileName;
    }

    public TutorSearchBean getTutorSearch() {
        return tutorSearch;
    }

    public void setTutorSearch(TutorSearchBean tutorSearch) {
        this.tutorSearch = tutorSearch;
    }

    public Integer getAutoSelectCount() {
        return autoSelectCount;
    }

    public void setAutoSelectCount(Integer autoSelectCount) {
        this.autoSelectCount = autoSelectCount;
    }

    public TutorCallBean getTutorCall() {
        return tutorCall;
    }

    public void setTutorCall(TutorCallBean tutorCall) {
        this.tutorCall = tutorCall;
    }

    public TutorService getService() {
        return service;
    }

    public void setService(TutorService service) {
        this.service = service;
    }

    public TutorCallService getCallService() {
        return callService;
    }

    public void setCallService(TutorCallService callService) {
        this.callService = callService;
    }

    public String getTutorIds() {
        return tutorIds;
    }

    public void setTutorIds(String tutorIds) {
        this.tutorIds = tutorIds;
    }

    @Override
    protected List<TutorBean> getBeanList() throws BaseException {
        List<TutorBean> tutorList = service.findTutorWithoutPage(getSearchCondition(), tutorSearch);
        if (autoSelectCount == null) {
            return tutorList;
        }
        Set<Integer> indexSet = BaseUtil.getRandomIndex(tutorList.size(), autoSelectCount);
        List<TutorBean> retList = new ArrayList<TutorBean>();
        Iterator<Integer> it = indexSet.iterator();
        while (it.hasNext()) {
            retList.add(tutorList.get(it.next()));
        }
        return retList;
    }

    @Override
    protected long getTotalCount() throws BaseException {
        long count = service.getTutorCount(tutorSearch);
        if (autoSelectCount == null) {
            return count;
        }
        if (count < autoSelectCount) {
            return count;
        } else {
            return autoSelectCount;
        }
    }

    public String export() throws BaseException {
        ByteArrayOutputStream baos = null;
        try {
            String rootPath = ServletActionContext.getServletContext().getRealPath("/");
            String templatePathSingle = rootPath + "WEB-INF\\conf\\tutor\\"
                    + TutorExcelAction.XLS_TUTOR_TEMPLATE;
            String templatePathMulti = rootPath + "WEB-INF\\conf\\tutor\\"
                    + TutorExcelAction.XLS_TUTOR_LIST_TEMPLATE;
            List<TutorBean> list = getBeanList();
            List<TutorExcelBean> excelList = getExcelBeanList(list);

            Workbook wb = null;
            if (excelList.size() == 1) {
                wb = getService().exportTutor(templatePathSingle, excelList);
            } else {
                wb = getService().exportTutor(templatePathMulti, excelList);
            }
            baos = new ByteArrayOutputStream();
            wb.write(baos);
            baos.flush();
            byte[] excelBytes = baos.toByteArray();
            excelStream = new ByteArrayInputStream(excelBytes, 0, excelBytes.length);

            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            downloadFileName = "老师信息详细_" + sf.format(new Date()) + ".xls";
            downloadFileName = new String(downloadFileName.getBytes(), "ISO8859-1");
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("导出Excel失败！", e);
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
            }
        }
        return SUCCESS;
    }

    public String saveAutoSelectTutorCall() {
        map = new HashMap<String, Object>();
        try {
            if (tutorIds == null || tutorIds.isEmpty()) {
                throw new BaseException("错误：没有选择老师！");
            }
            String[] targetIds = tutorIds.split(",");
            List<TutorCallBean> callBeanList = new ArrayList<TutorCallBean>();
            for (String id : targetIds) {
                Integer targetId = Integer.valueOf(id);
                TutorCallBean call = new TutorCallBean();
                TutorBean tutor = new TutorBean();
                tutor.setId(targetId);
                call.setTarget(tutor);
                call.setCallName(tutorCall.getCallName());
                call.setCallReason(tutorCall.getCallReason());
                call.setCallRemark(tutorCall.getCallRemark());
                call.setCallAim(tutorCall.getCallAim());

                callBeanList.add(call);
            }

            callService.saveTutorCall(callBeanList);
            return SUCCESS;
        } catch (BaseException e) {
            map.put("errorMsg", e.getMessage());
            return ERROR;
        }
    }

    private List<TutorExcelBean> getExcelBeanList(List<TutorBean> tutorList) {
        List<TutorExcelBean> beanList = new ArrayList<TutorExcelBean>();
        if (tutorList == null || tutorList.isEmpty()) {
            return beanList;
        }

        for (TutorBean tutor : tutorList) {
            beanList.add(new TutorExcelBean(tutor));
        }
        return beanList;
    }
}

